#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Autor: Josep Torrens Amer
# E-mail: toram74@gmail.com
#
# GNU GPL License, (C) 2007.
#
# Module: pool
#
# Description: Modul pool 
#
# Version: 0.0.1
#
# Created: 27-08-2007
#
# Modified:
#

class pool:
		"""
			Pool 
		"""
		_pool = {}

		def __init__ (self, db) :
		 		self._db = db

		def get (self, tObj) :
			"""
			Retorna un objecte
			"""

			# Obtenim parametres de la consulta
			cond = ""
			for p in tObj.GetParams():
					cond +="AND "+ p['camp']+"  "+p['cond']
					if p['tipus']=="numero" :
						cond +=  p['valor']
					else:
						cond +="'"+p['valor']+ "' "

			# Llevam la primera coma
			if cond.startswith("AND ") :
				cond = cond[4:]

			sql = "SELECT * FROM %s WHERE (%s)" % (tObj.nom, cond)

			res = self._db.Cursor(sql)
			return res





		def set ( self, tObj ):
			"""
			Actualitza un objecte
			"""

			# Obtenim parametres de la consulta
			cond = ""
			for p in tObj.GetParams():
					cond +="AND "+ p['camp']+"  "+p['cond']
					if p['tipus']=="numero" :
						cond +=  p['valor']
					else:
						cond +="'"+p['valor']+ "' "

			camps = ""
			# Obtenim camps a actualitzar
			for p in tObj.GetFields():
					camps+=", "+ p['camp']+"  = "
					if p['tipus']=="numero" :
						camps +=  p['valor']
					else:
						camps +="'"+p['valor']+ "' "

			# Llevam la primera coma
			if cond.startswith("AND ") :
				cond = cond[4:]

			if camps.startswith(", ") :
				camps = camps[1:]

			sql = "UPDATE %s SET %s WHERE (%s)" % (tObj.nom, camps, cond)

			res = self._db.Cursor(sql)
			return res




		def ins ( self, tObj ):
			"""
			Inserta un objecte
			"""
			camps = ""
			valors = ""
			# Obtenim camps a insertar
			for p in tObj.GetFields():
					camps+=", "+ p['camp']
					if p['tipus']=="numero" :
						valors +=  p['valor']
					else:
						valors +="'"+p['valor']+ "' "

			# Llevam la primera coma
			if valors.startswith(", ") :
				valors = valors[2:]

			if camps.startswith(", ") :
				camps = camps[1:]

			sql = "INSERT INTO %s (%s) VALUES (%s)" % (tObj.nom, camps, valors)

			res = self._db.Cursor(sql)
			return res


		def eli ( self, tObj ):
			"""
			Borra un objecte
			"""
	
			# Obtenim parametres de la consulta
			cond = ""
			for p in tObj.GetParams():
					cond +="AND "+ p['camp']+"  "+p['cond']
					if p['tipus']=="numero" :
						cond +=  p['valor']
					else:
						cond +="'"+p['valor']+ "' "

			if cond.startswith("AND ") :
				cond = cond[4:]

			sql = "DELETE FROM %s WHERE (%s)" % (tObj.nom, cond)

			res = self._db.Cursor(sql)
			return res




 		def find (self, tObj):	
 				pass


				

